<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500"  destroy-on-close @closed="$emit('closed')" align-center>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button type="primary" color="#6074e8" @click="to_export">导出</el-button>
        <el-main class="printMain" ref="printMain">
            <div class="title">杭州威大纺织有限公司</div>
            <table border="1" style="border-collapse: collapse; width: 100%;">
                <thead>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" colspan="17">*** 成品明细单 ***</th>
                    </tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border">客户</th>
                        <th class="table_border" colspan="7">卡诺</th>
                        <th class="table_border" colspan="2">发货日期</th>
                        <th class="table_border" colspan="3">{{detail.send_date}}</th>
                        <th class="table_border" colspan="2">出库单号</th>
                        <th class="table_border" colspan="2">{{detail.send_code}}</th>
                    </tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" style="width: 150px">品名</th>
                        <th class="table_border">货号</th>
                        <th class="table_border">花型</th>
                        <th class="table_border">颜色</th>
                        <!-- 固定的10列码数 -->
                        <th class="table_border">1</th>
                        <th class="table_border">2</th>
                        <th class="table_border">3</th>
                        <th class="table_border">4</th>
                        <th class="table_border">5</th>
                        <th class="table_border">6</th>
                        <th class="table_border">7</th>
                        <th class="table_border">8</th>
                        <th class="table_border">9</th>
                        <th class="table_border">10</th>
                        <!-- 合计列 -->
                        <th class="table_border">匹数</th>
                        <th class="table_border">码数</th>
                        <th class="table_border">重量</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 按品名(goods_name)、花型(flower)和颜色(color)分组循环展示数据 -->
                    <template v-for="(goodsGroup, goodsIndex) in order_detail" :key="goodsIndex">
                        <template v-for="(flowerGroup, flowerIndex) in goodsGroup.flowerGroups" :key="flowerIndex">
                            <template v-for="(colorGroup, colorIndex) in flowerGroup.colorGroups" :key="colorIndex">
                                <!-- 每组数据的详细行 -->
                                <template v-for="(codeGroup, groupIndex) in colorGroup.codeGroups" :key="groupIndex">
                                    <tr>
                                        <!-- 品名列 - 合并单元格 -->
                                        <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="flowerIndex === 0 && colorIndex === 0 && groupIndex === 0">
                                            {{goodsGroup.goods_name}}
                                        </td>
                                        <!-- 货号列 - 合并单元格 -->
                                        <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="flowerIndex === 0 && colorIndex === 0 && groupIndex === 0">
                                            {{goodsGroup.goods_code}}
                                        </td>
                                        <!-- 花型列 - 合并单元格 -->
                                        <td class="table_border" :rowspan="flowerGroup.totalRows" v-if="colorIndex === 0 && groupIndex === 0">
                                            {{flowerGroup.flower}}
                                        </td>
                                        <!-- 颜色列 - 合并单元格 -->
                                        <td class="table_border" :rowspan="colorGroup.totalRows" v-if="groupIndex === 0">
                                            {{colorGroup.color}}
                                        </td>
                                        <!-- 码数列 - 每组最多10个码数 -->
                                        <template v-for="(codeValue, codeIndex) in codeGroup" :key="codeIndex">
                                            <td class="table_border">{{codeValue || ''}}</td>
                                        </template>
                                        <!-- 填充剩余的码数列 -->
                                        <template v-for="n in (10 - codeGroup.length)" :key="'empty-' + n">
                                            <td class="table_border"></td>
                                        </template>
                                        <!-- 合计列 - 合并单元格，与颜色列相同 -->
                                        <td class="table_border" :rowspan="colorGroup.totalRows" v-if="groupIndex === 0">
                                            {{colorGroup.total_count}}
                                        </td>
                                        <td class="table_border" :rowspan="colorGroup.totalRows" v-if="groupIndex === 0">
                                            {{colorGroup.total_number}}
                                        </td>
                                        <td class="table_border" :rowspan="colorGroup.totalRows" v-if="groupIndex === 0">
                                            {{colorGroup.total_weight}}
                                        </td>
                                    </tr>
                                </template>
                            </template>
                        </template>
                        <!-- 品名合计行 -->
                        <tr style="background-color: #dce6f1;">
                            <td class="table_border"></td>
                            <td class="table_border"></td>
                            <td class="table_border"></td>
                            <td class="table_border" style="text-align: center; font-weight: bold;">小计</td>
                            <!-- 填充10个码数列 -->
                            <template v-for="n in 10" :key="'subtotal-code-' + n">
                                <td class="table_border"></td>
                            </template>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_count}}</td>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_number_sum}}</td>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_weight_sum}}</td>
                        </tr>
                    </template>
                </tbody>
                <!-- 汇总表总合计行 - 按图片红框格式 -->
                <tfoot>
                    <!-- 收货说明行 -->
                    <tr>
                        <td class="table_border" colspan="10" rowspan="2">贵司收到货时，请随即验收,若品质、数量有问题时，贵司应于收货之日起七日内将货运回我司或书面通知我司，派人会员检验。若逾期通知或经贵司染整、裁剪、或其它的加工行为，即认为贵司同意其品质、数量、规格符合要求，日后不得异议。</td>
                        <td class="table_border" style="font-weight: bold;" colspan="4">合计</td>
                        <td class="table_border" style="font-weight: bold;">{{summaryGrandTotals.total_count}}</td>
                        <td class="table_border" style="font-weight: bold;">{{summaryGrandTotals.total_number_sum}}</td>
                        <td class="table_border" style="font-weight: bold;">{{summaryGrandTotals.total_weight_sum}}</td>
                    </tr>
                    <!-- 签名行 -->
                    <tr>
                        <!-- <td class="table_border" colspan="10"></td> -->
                        <td class="table_border" colspan="2">核决</td>
                        <td class="table_border" colspan="2">仓管</td>
                        <td class="table_border">客户签收</td>
                        <td class="table_border"></td>
                        <td class="table_border"></td>
                    </tr>
                    <!-- 业务备注行 -->
                    <tr>
                        <td class="table_border" colspan="10">一、业务（白）二、客户（红）三、回签财务（黄）</td>
                        <td class="table_border" colspan="2"></td>
                        <td class="table_border" colspan="2"></td>
                        <td class="table_border"></td>
                        <td class="table_border"></td>
                        <td class="table_border"></td>
                    </tr>
                </tfoot>
            </table>
        </el-main>
	</el-dialog>
</template>

<script>
import print from '@/utils/print'
export default {
	emits: ['success', 'closed'],
	data() {
			return {
				dialog: {
					client: false
				},
				mode: "add",
				titleMap: {
					print: '打印',
				},
				visible: false,
                id: "",
                detail: {},
                order_detail: [],
                summary_detail: [], // 按品名汇总的数据，花型用/合并，数量合计
				grandTotals: { // 所有品名的总合计
					total_count: 0, // 总匹数
					total_number_sum: 0, // 总总码数
					total_meter_sum: 0, // 总金额
					total_weight_sum: 0, // 总金额
				},
				summaryGrandTotals: { // 汇总表的总合计
					total_count: 0, // 总件数
					total_number_sum: 0, // 总总数量
					total_meter_sum: 0, // 总金额
					total_weight_sum: 0, // 总金额
				}
			}
		},
	mounted() {
	},
	methods: {
        print(){
            const fileName = this.detail.send_code ? `明细码单_${this.detail.send_code}` : '明细码单';
            print(this.$refs.printMain, { title: fileName });
            setTimeout(()=>{
                this.visible = false
            },500)
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
        async setData(data) {
            this.id = data.id
            var res = await this.$API.ware.ware.send.detail.get({id: data.id});
            this.detail = res.data;
            // 先创建一个临时对象，用于统计相同goods_name、flower和color的数量和合计值
            const uniqueMap = new Map()
            // 遍历数据，合并相同goods_name、flower和color的数据
            res.data.detail.forEach(item => {
                const key = `${item?.inspect.goods_name}_${item?.inspect.flower}_${item?.inspect.color_en}`
                if (!uniqueMap.has(key)) {
                    // 如果是新的组合，创建新对象
                    uniqueMap.set(key, {
                        goods_id: item?.inspect.goods_id,
                        goods_name: item?.inspect.goods_name,
                        goods_code: item?.inspect.goods_code,
                        flower: item?.inspect.flower,
                        color: item?.inspect.color_en,
                        unit_name: "码",
                        number: 1, // 初始数量为1
                        total_meter: Number(item?.inspect?.meter) || 0,
                        total_number: Number(item?.inspect?.code_number) || 0,
                        weight: Number(item?.inspect?.net_weight) || 0,
                        total_weight: Number(item?.inspect?.net_weight) || 0,
                        remark: item.remark,
                        code_values: [Number(item?.inspect?.code_number) || 0] // 存储每个码数的值
                    })
                } else {
                    // 如果已存在该组合，累加数量和合计值
                    const existingItem = uniqueMap.get(key)
                    existingItem.number += 1
                    existingItem.total_number += Number(item?.inspect?.code_number) || 0
                    existingItem.total_meter += Number(item?.inspect?.meter) || 0
                    existingItem.total_weight += Number(item?.inspect?.net_weight) || 0
                    existingItem.code_values.push(Number(item?.inspect?.code_number) || 0) // 添加码数值
                }
            })
            // 将Map转换为数组
            let array = Array.from(uniqueMap.values()).map(item => ({
                ...item,
                equal_weight: item.number > 0 ? (item.total_weight / item.number).toFixed(2) : '0.00', // 计算平均重
                equal_code: item.number > 0 ? (item.total_number / item.number).toFixed(2) : '0.00', // 计算均码
                total_number: (item.total_number).toFixed(2), // 格式化总码数
                total_meter: (item.total_meter).toFixed(2), // 格式化总码数
                total_weight: (item.total_weight).toFixed(2), // 格式化总重量
            }))
            // 按goods_name、flower和color分组数据，并计算合计
            this.order_detail = this.groupDataByGoodsAndFlower(array)
            // 计算所有品名的总合计
            this.calculateGrandTotals(array)
            this.summary_detail = this.createSummaryData(array)
            this.calculateSummaryGrandTotals()
        },
        // 计算所有品名的总合计
        calculateGrandTotals(data) {
            let grandTotalCount = 0
            let grandTotalNumber = 0
            let grandTotalMeter = 0
            let grandTotalWeight = 0
            
            data.forEach(item => {
                grandTotalCount += item.number
                grandTotalNumber += parseFloat(item.total_number)
                grandTotalMeter += parseFloat(item.total_meter)
                grandTotalWeight += parseFloat(item.total_weight)
            })
            
            this.grandTotals = {
                total_count: grandTotalCount,
                total_number_sum: grandTotalNumber.toFixed(2),
                grandTotalMeter: grandTotalMeter.toFixed(2),
                grandTotalWeight: grandTotalWeight.toFixed(2)
            }
        },
        // 计算汇总表的总合计
        calculateSummaryGrandTotals() {
            let grandTotalCount = 0
            let grandTotalNumber = 0
            let grandTotalMeter = 0
            let grandTotalWeight = 0
            let grandTotalEqualWeight = 0
            let grandTotalEqualCode = 0
            
            // 直接从order_detail数组中累加各个品名分组的小计值
            this.order_detail.forEach(goodsGroup => {
                grandTotalCount += goodsGroup.total_count
                grandTotalNumber += parseFloat(goodsGroup.total_number_sum || 0)
                grandTotalMeter += parseFloat(goodsGroup.total_meter_sum || 0)
                grandTotalWeight += parseFloat(goodsGroup.total_weight_sum || 0)
                grandTotalEqualWeight += parseFloat(goodsGroup.equal_weight || 0)
                grandTotalEqualCode += parseFloat(goodsGroup.equal_code || 0)
            })
            
            // 计算总合计的总均重和总均码
            const equal_weight = grandTotalEqualWeight.toFixed(2);
            const equal_code = grandTotalEqualCode.toFixed(2);
            
            this.summaryGrandTotals = {
                total_count: grandTotalCount,
                total_number_sum: grandTotalNumber.toFixed(2),
                total_meter_sum: grandTotalMeter.toFixed(2),
                total_weight_sum: grandTotalWeight.toFixed(2),
                equal_weight: equal_weight,
                equal_code: equal_code
            }
        },
        // 创建按goods_name汇总的数组，合并花型并用/分隔，合计数量
        createSummaryData(data) {
            const summaryMap = new Map();
            
            // 遍历数据，按goods_name分组，合并花型并合计数量
            data.forEach(item => {
                const goodsName = item.goods_name;
                
                if (!summaryMap.has(goodsName)) {
                    summaryMap.set(goodsName, {
                        goods_id: item.goods_id,
                        goods_name: goodsName,
                        goods_code: item.goods_code,
                        flowers: new Set(), // 使用Set存储唯一的花型
                        total_count: 0, // 合计件数
                        total_number_sum: 0, // 合计总数量
                        total_meter_sum: 0, // 合计米数
                        total_weight_sum: 0, // 合计重量
                        total_equal_weight_sum: 0, // 合计均重
                        total_equal_code_sum: 0, // 合计均码
                        unit_name: item.unit_name
                    });
                }
                
                const summary = summaryMap.get(goodsName);
                summary.flowers.add(item.flower); // 添加花型到Set中
                summary.total_count += item.number;
                summary.total_number_sum += parseFloat(item.total_number);
                summary.total_meter_sum += parseFloat(item.total_meter);
                summary.total_weight_sum += parseFloat(item.total_weight);
                summary.total_equal_weight_sum += parseFloat(item.equal_weight || 0);
                summary.total_equal_code_sum += parseFloat(item.equal_code || 0);
            });
            
            // 转换为数组，处理花型合并和格式化数值
            const result = Array.from(summaryMap.values()).map(item => ({
                ...item,
                flowers: Array.from(item.flowers).join('/'), // 用/分隔合并花型
                total_number_sum: item.total_number_sum.toFixed(2),
                total_meter_sum: item.total_meter_sum.toFixed(2),
                total_weight_sum: item.total_weight_sum.toFixed(2),
                equal_weight: item.total_equal_weight_sum.toFixed(2),
                equal_code: item.total_equal_code_sum.toFixed(2)
            }));
            
            return result;
        },
        // 按goods_name、flower和color分组数据
        groupDataByGoodsAndFlower(data) {
            // 创建一个Map来存储每个goods_name的分组
            const goodsMap = new Map();
            
            // 遍历数据，按goods_name、flower和color分组
            data.forEach(item => {
                const goodsName = item.goods_name;
                const flower = item.flower;
                const color = item.color;
                
                // 如果goods_name不存在于Map中，创建新的goods分组
                if (!goodsMap.has(goodsName)) {
                    goodsMap.set(goodsName, {
                        goods_id: item.goods_id,
                        goods_name: goodsName,
                        goods_code: item.goods_code,
                        flowerGroups: [],
                        totalRows: 0, // 该品名的总行数(包括明细和合计行)
                        total_count: 0, // 合计匹数
                        total_number_sum: 0, // 合计总码数
                        total_meter_sum: 0, // 合计米数
                        total_weight_sum: 0, // 合计重量
                        total_equal_weight_sum: 0, // 合计均重
                        total_equal_code_sum: 0, // 合计均码
                    });
                }
                
                const goodsGroup = goodsMap.get(goodsName);
                
                // 查找当前flower的分组
                let flowerGroup = goodsGroup.flowerGroups.find(group => group.flower === flower);
                
                // 如果flower分组不存在，创建新的flower分组
                if (!flowerGroup) {
                    flowerGroup = {
                        flower: flower,
                        colorGroups: [],
                        totalRows: 0 // 该花型的总行数
                    };
                    goodsGroup.flowerGroups.push(flowerGroup);
                }
                
                // 查找当前color的分组
                let colorGroup = flowerGroup.colorGroups.find(group => group.color === color);
                
                // 如果color分组不存在，创建新的color分组
                if (!colorGroup) {
                    // 将码数值按每10个一组分组
                    const codeGroups = this.groupArrayBySize(item.code_values, 10);
                    
                    colorGroup = {
                        color: color,
                        codeGroups: codeGroups,
                        totalRows: codeGroups.length, // 该颜色的总行数（由码数分组数量决定）
                        total_count: item.number, // 该颜色的总匹数
                        total_number: item.total_number, // 该颜色的总码数
                        total_weight: item.total_weight // 该颜色的总重量
                    };
                    flowerGroup.colorGroups.push(colorGroup);
                }
                
                // 更新品名的合计值
                goodsGroup.total_count += item.number;
                goodsGroup.total_number_sum += parseFloat(item.total_number);
                goodsGroup.total_meter_sum += parseFloat(item.total_meter);
                goodsGroup.total_weight_sum += parseFloat(item.total_weight);
                goodsGroup.total_equal_weight_sum += parseFloat(item.equal_weight);
                goodsGroup.total_equal_code_sum += parseFloat(item.equal_code);
            });
            
            // 计算每个goods分组和flower分组的总行数
            const result = Array.from(goodsMap.values());
            result.forEach(goodsGroup => {
                // 计算每个flower分组的总行数
                goodsGroup.flowerGroups.forEach(flowerGroup => {
                    flowerGroup.totalRows = flowerGroup.colorGroups.reduce((total, colorGroup) => total + colorGroup.totalRows, 0);
                });
                
                // 计算每个goods分组的总行数（包括明细行和合计行）
                goodsGroup.totalRows = goodsGroup.flowerGroups.reduce((total, flowerGroup) => total + flowerGroup.totalRows, 0);
                
                // 格式化合计值
                goodsGroup.total_number_sum = (goodsGroup.total_number_sum).toFixed(2);
                goodsGroup.total_meter_sum = (goodsGroup.total_meter_sum).toFixed(2);
                goodsGroup.total_weight_sum = (goodsGroup.total_weight_sum).toFixed(2);
                
                // 计算品名合计的总均重和总均码
                goodsGroup.equal_weight = goodsGroup.total_equal_weight_sum.toFixed(2);
                goodsGroup.equal_code = goodsGroup.total_equal_code_sum.toFixed(2);
            });
            
            return result;
        },
        
        // 将数组按指定大小分组
        groupArrayBySize(array, size) {
            const groups = [];
            for (let i = 0; i < array.length; i += size) {
                groups.push(array.slice(i, i + size));
            }
            return groups;
        },


        async to_export(){
            var res = await this.$API.ware.ware.code_detail_export.get({id: this.id})
            if (res.code == 1) {
				this.$message.success("导出成功");
				window.location.href = res.data.url
			} else {
				this.$alert(res.message, "提示", {type: "error"});
			}
        },
        
	}
}
</script>

<style lang="scss">
.printMain{
    .title {
        font-size: 20px;
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px;
    }
    td{
        text-align: center;
    }
    .table_border{
        width: 70px;
        height: 32px;
        border: 1px solid #000;
    }
    table{
        width: 100%;
        tbody{
            font-size: 13px;
            tr {
                page-break-inside: avoid;
                -webkit-region-break-inside: avoid; 
            }
            tr:last-child{
                page-break-after: avoid;
            }
        }
        th {
            font-weight: bold;
            background-color: #f0f0f0;
        }
    } 
}
</style>
